package com.ruoyi.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dyun.tool.mybatis.domain.PageDomain;
import com.ruoyi.common.annotation.SysLog;
import com.ruoyi.common.enums.BusinessTypeEnum;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.support.DateRange;
import com.ruoyi.project.system.entity.SysConfig;
import com.ruoyi.project.system.service.SysConfigService;
import lombok.AllArgsConstructor;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.$;
import net.dreamlu.mica.core.validation.CreateGroup;
import net.dreamlu.mica.core.validation.UpdateGroup;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 参数配置 控制层
 *
 * @author dy
 */
@RestController
@RequestMapping("/system/config")
@AllArgsConstructor
public class SysConfigController extends BaseController {

    private final SysConfigService sysConfigService;

    /**
     * 分页
     */
    @PreAuthorize("@ss.hasPermi('system:config:list')")
    @GetMapping("/list")
    public R<IPage<SysConfig>> list(SysConfig sysConfig, PageDomain pageDomain, DateRange dateRange) {
        IPage<SysConfig> pages = sysConfigService.page(startPage(pageDomain), new LambdaQueryWrapper<SysConfig>()
                .like($.isNotBlank(sysConfig.getConfigName()), SysConfig::getConfigName, sysConfig.getConfigName())
                .eq($.isNotBlank(sysConfig.getConfigType()), SysConfig::getConfigType, sysConfig.getConfigType())
                .like($.isNotBlank(sysConfig.getConfigKey()), SysConfig::getConfigKey, sysConfig.getConfigKey())
                .between($.isAnyNotBlank(dateRange.getBeginTime(), dateRange.getEndTime()), SysConfig::getCreateTime, dateRange.getBeginTime(), dateRange.getEndTime()));
        return success(pages);
    }

    /**
     * 详情
     */
    @PreAuthorize("@ss.hasPermi('system:config:query')")
    @GetMapping("/detail")
    public R<SysConfig> detail(Long id) {
        return success(sysConfigService.getById(id));
    }

    /**
     * 根据参数键名查询参数值
     */
    @GetMapping(value = "/configKey/{configKey}")
    public R getConfigKey(@PathVariable String configKey) {
        // 外显的都配置成非系统内置
        SysConfig sysConfig = sysConfigService.getOne(new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getConfigKey, configKey)
                .eq(SysConfig::getConfigType, "N"));
        if (sysConfig != null) {
            return success(sysConfig.getConfigValue());
        }
        return success();
    }

    /**
     * 新增
     */
    @PreAuthorize("@ss.hasPermi('system:config:add')")
    @SysLog(title = "参数配置", businessType = BusinessTypeEnum.INSERT)
    @PostMapping("/add")
    public R add(@Validated(value = {CreateGroup.class}) @RequestBody SysConfig sysConfig) {
        int sysConfigNum = sysConfigService.count(new LambdaQueryWrapper<SysConfig>()
                .eq($.isNotBlank(sysConfig.getConfigKey()), SysConfig::getConfigKey, sysConfig.getConfigKey()));
        if (sysConfigNum > 0) {
            return fail("新增参数[" + sysConfig.getConfigName() + "]失败，参数键名已存在");
        }
        return status(sysConfigService.saveIgnore(sysConfig));
    }

    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('system:config:edit')")
    @SysLog(title = "参数配置", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping("/update")
    public R update(@Validated(value = {UpdateGroup.class}) @RequestBody SysConfig sysConfig) {
        SysConfig checkSysConfig = sysConfigService.getOne(new LambdaQueryWrapper<SysConfig>()
                .eq($.isNotBlank(sysConfig.getConfigKey()), SysConfig::getConfigKey, sysConfig.getConfigKey()));
        if (checkSysConfig != null && !checkSysConfig.getId().equals(sysConfig.getId())) {
            return fail("修改参数[" + sysConfig.getConfigName() + "]失败，参数键名已存在");
        }
        return status(sysConfigService.updateById(sysConfig));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @SysLog(title = "参数配置", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/delete/{ids}")
    public R delete(@PathVariable Long[] ids) {
        List<SysConfig> sysConfigs = new ArrayList<>();
        List<Long> idList = new ArrayList<>(Arrays.asList(ids));
        idList.forEach(v -> {
            SysConfig sysConfig = new SysConfig();
            sysConfig.setId(v);
            sysConfigs.add(sysConfig);
        });
        boolean result = sysConfigService.updateBatchById(sysConfigs) && sysConfigService.removeByIds(idList);
        return status(result);
    }
}